<template>
  <el-dialog :title="`${row?.id ? '编辑' : '新增'}角色`" :model-value="modelValue" width="700px" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="name" label="角色名称">
            <el-input class="form-width" placeholder="角色名称" v-model="formValue.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status" label="角色状态：">
            <el-radio-group v-model="formValue.status">
              <el-radio v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序">
            <el-input-number v-model="formValue.sort" :min="1" :max="9999" controls-position="right"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="菜单权限" prop="menuIds" class="w-full">
            <el-tree
              ref="treeRef"
              :data="menus"
              node-key="id"
              show-checkbox
              :props="{ children: 'children', label: 'name' }"
              :expand-on-click-node="false"
              v-model:default-expanded-keys="expandedKeys"
              class="w-full"
              @check="commEvent.onCheckChange"
            >
            </el-tree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, PropType, watch, nextTick } from "vue"
import { ElMessage, FormInstance, FormRules, TreeInstance } from "element-plus"
import { statusOptions } from "@/utils/dict"
import { getMenuTreeApi, getRoleMenuIdsApi, saveRoleApi } from "@/api/modules/system"
import { SystemSpace } from "@/api/interface/system"
const props = defineProps({
  modelValue: Boolean,
  row: { type: Object as PropType<SystemSpace.RolePageList>, default: () => {} }
})
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
const treeRef = ref<TreeInstance>() // 树实例
const menus = ref<SystemSpace.MenuTree[]>([]) // 部门树
const expandedKeys = ref<number[]>([]) // 默认展开的节点
// 表单数据
const formValue = ref({
  name: "",
  status: 0,
  sort: 1
})
// 表单校验规则
const rules: FormRules = {
  name: [{ required: true, message: "请输入户角色", trigger: "blur" }]
}
// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 获取菜单信息
  getMenus: async () => {
    const { data } = await getMenuTreeApi({})
    menus.value = data
  },
  // 获取菜单编号
  getMenuIds: async (id: number) => {
    const { name, status, sort } = props.row
    formValue.value = { name, status, sort }
    const { data: menuIds } = await getRoleMenuIdsApi({ id })
    menuIds.forEach((item: number) => {
      treeRef.value?.setChecked(item, true, false)
    })
  },
  // 菜单权限勾选
  onCheckChange: (item: any) => {
    const checkedKeys = treeRef.value?.getCheckedKeys() || []
    if (!checkedKeys.includes(item.id) && item.type === 2) {
      treeRef.value?.setChecked(item.pid, true, false)
    }
  },
  // 表单提交
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      const menuIds: number[] = [
        ...(treeRef.value?.getHalfCheckedKeys() || []),
        ...(treeRef.value?.getCheckedKeys() || [])
      ] as number[]
      const params: SystemSpace.RoleAdd = { ...formValue.value, roleKey: "other", menuIds }
      if (props.row?.id) {
        params.id = props.row.id
        params.roleKey = props.row.roleKey
      }
      const { code } = await saveRoleApi(params)
      if (code !== "200") return
      ElMessage.success("操作成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  flag => {
    if (flag) {
      nextTick(() => {
        formRef.value?.resetFields()
        treeRef.value?.setCheckedKeys([])
        commEvent.getMenus()
        if (props.row?.id) {
          commEvent.getMenuIds(props.row.id)
        }
      })
    }
  }
)
</script>

<style scoped></style>
